package com.example.hotelback.controller;

import com.example.hotelback.utils.JwtUtils;
import com.example.hotelback.utils.Result;
import com.example.hotelback.entity.Admin;
import com.example.hotelback.exception.CustomException;
import com.example.hotelback.service.AdminService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    /**
     * 登录
     * @param admin
     * @return
     */
    @ApiOperation("管理员登录")
    @PostMapping("/login")
    @ResponseBody // 返回给浏览器
    public Result login(@RequestBody Admin admin) {
        try {
            Admin loginAdmin = adminService.findByCond(admin.getName(), admin.getPassword()); // 获取管理员信息
            String token = JwtUtils.generateToken(loginAdmin.getId(), loginAdmin.getName()); // 生成token
            loginAdmin.setToken(token);
            return Result.success(loginAdmin);
        } catch (CustomException e) {
            return Result.error(e.getMsg());
        }
    }

    /**
     * 管理员查看个人信息
     * @param id
     * @return
     */
    @ApiOperation("管理员查看个人信息")
    @GetMapping("/find")
    @ResponseBody
    public Result find(int id) {
        Admin admin = adminService.findById(id);
        return Result.success(admin); // 能登录就一定有对应管理员
    }

}
